#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *parse_scheme(const char *url)
{
    char *p = strstr(url,"://");
    if (p == NULL) {
        printf("url 非法\t%s\n",url);
        exit(1);
    }

    char *scheme = strndup(url,p-url);

    return scheme;
}

/**
 * http://a.com/bbb
 * http://a.com?b=/c
 * http://a.com:8080#ddd
 * http://a.com
 */
char *parse_host(const char *url)
{
    char a[3] = {'/','?','#'};
    char *s = NULL;
    int p = 0;
    int min = 0;

    for(int i=0;i < 3;i++) {
        s = strchr(url,a[i]);
        if(s != NULL) {
            p = s-url;
            if(i == 0 || min > p) {
                min = p;
            }
        }
    }

    if (min == 0) {
        min = strlen(url);
    }

    char *host = strndup(url,min);

    return host;
}

int main(int argc, char *argv[])
{
    //const char *url = "http://static.mengkang.net:8080/abc.jpg";
    
    if(argc < 2){
        printf("%s\n","请输入url");
        exit(1);
    }

    const char *url = argv[1];
    
    char *scheme = parse_scheme(url);
    printf("scheme\t%s\n",scheme);
    
    url = url + strlen(scheme) + strlen("://");

    char *host = parse_host(url);

    printf("host\t%s\n",host);

    free(scheme);
    free(host);
    
    return 0;
}
